<?php
namespace app\index\controller;
use \think\captcha\Captcha;
use \think\Db;
use \think\Request;
use \Firebase\JWT\JWT;

class Index
{
    public $user = NULL;
    public $key='EzSTE2CgX0kz0Wu3';
    public function __construct()
    {

    }

    public function index()
    {
        return view('index');
    }

    public function vcode(){
		ob_clean();
        $captcha = new Captcha();
        return $captcha->entry();
    }

    public  function  do_post($url,$params,$headers = array(),$https=false){
        $_headers=array(
            "Content-Type: application/x-www-form-urlencoded",
            "X-Requested-With: XMLHttpRequest"
        );
        foreach ($headers as $val){
            $_headers[] = $val;
        }

        $postData = http_build_query($params);

        $_headers[] = 'Content-Length: ' . strlen($postData);

        $ch = curl_init ();

        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'POST' );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $postData );
        curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
        curl_setopt ( $ch, CURLOPT_TIMEOUT, 60 );

        if ($https) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在
        }

        $result = curl_exec ( $ch );
        curl_close ( $ch );

        return $result;
    }

    /*public function test(){
        $pdata = [
            "amount" => '194.00',
            "created_at"=>"2019-09-22 22:07:33",
            "num" => '200.00',
            "order_no" => "1909221007337103",
            "payment" => "alipay",
            "uuid" =>  'V1909222207364541',
            'sign'=>'A68DB1BEB7A7F215A939FE155BF2CCC5'
        ];
        $params = "";
        foreach ($pdata as $key=>$val){
            $params .= $key."=".$val."&";
        }
        $params = substr($params,0,-1);
        $key = "3NgGRHLN5SKryJjDA2";
        //amount=194.00&created_at=2019-09-22 21:25:33&num=200.00&payment=alipay&uuid=U1909222125475081&order_no=1909220925332655&sign=F95269512F3FFFBA83379620F18A590F
        //echo http_build_query($pdata);echo '<br/>';
        //echo $params;echo '<br/>';
        //echo strtoupper(md5('amount=194.00&created_at=2019-09-22 22:07:33&num=200.00&order_no=1909221007337103&payment=alipay&uuid=V1909222207364541'.$key));echo '<br/>';
        //$pdata['sign'] = strtoupper(md5($params.'3NgGRHLN5SKryJjDA2'));
         //echo $pdata['sign'];die();

        //$content = 'params='.json_encode($params);

        //$response = $this->tocurl("http://api.wshxw.com/api/store/order",$headers,$params);

        $response = $this->do_post("https://www.bu02w.cn/Notpy.notify2.do",$pdata,array(),true);
        var_dump($response);
    }

    public function test_rq(){
        $info = Request::instance()->header("device-info");
       var_dump($info);
    }*/

    private function getUserLevel($level){
        switch ($level){
            case 0:
                return '未开通会员';
            case 1:
                return 'V1 普通会员';
            case 2:
                return 'V2 黄金会员';
            case 3:
                return 'V3 白金会员';
            case 4:
                return 'V4 钻石会员';
            case 5:
                return 'V5 超级会员';
        }
        return '未知等级';
    }

    protected function verifyJwt($jwt)
    {
        $key = md5('fdsfe4gfgs');
        // JWT::$leeway = 3;
        try {
            $jwtAuth = json_encode(JWT::decode($jwt, $key, array('HS256')));
            $authInfo = json_decode($jwtAuth, true);
            if (!empty($authInfo['user_id'])) {
                return intval($authInfo['user_id']);
            } else {
                echo json_encode([
                    'code' => -1,
                    'msg' => 'Token验证不通过,用户不存在'
                ]);
            }
        } catch (\Firebase\JWT\SignatureInvalidException $e) {
            echo json_encode([
                'code' => -1,
                'msg' => 'Token无效'
            ]);
            exit;
        } catch (\Firebase\JWT\ExpiredException $e) {
            echo json_encode([
                'code' => -1,
                'msg' => 'Token过期'
            ]);
            exit;
        } catch (Exception $e) {
            echo json_encode([
                'code' => -1,
                'msg' => '系统错误，请稍候重试'
            ]);
            exit;
        }
    }

    private function getUserInfo($uid=0){
        if($uid){
            $user = Db::name("user")->alias("u")->join("kl_member_info m","u.id=m.user_id","LEFT")->where('u.id',$uid)->where('u.user_type','member')->find();
            if(!$user) return NULL;
        }else{
            $header = Request::instance()->header();//var_dump($header);die();
            if (!isset($header['token']) || $header['token'] == 'null') {
                return NULL;
            }else{
                $uid = $this->verifyJwt($header['token']);
                $user = Db::name("user")->alias("u")
                    ->join("kl_member_info m","u.id=m.user_id","LEFT")
                    ->where('u.id',$uid)
                    ->where('u.user_type','member')->find();
                if(!$user) return NULL;
            }
        }


        $this->user = $user;
        $this->user['id'] = $user['user_id'];
        $data = ['id'=>$user['user_id'],'username'=>$user['username'],'usernick'=>$user['usernick'],'tuijianma'=>$user['tuijianma'],
                'money'=>$user['money'],'vip_level'=>$this->getUserLevel($user['vip_level']),'offers_days'=>$user['offers_days'],'free_times'=>$user['free_times'],
                'tuijian_count'=>$user['tuijian_count'],'end_time'=>$user['end_time'] ? ($user['end_time']>=time() ?  date('Y-m-d H:i:s',$user['end_time']) :'已到期') : '','
                last_login_time'=>$user['last_login_time'] ? date('Y-m-d H:i:s',$user['last_login_time']) : ''];
        $data['server_qq'] = Db::name("user")->where("id",$user['parent_id'])->value("qq");
        if(strlen($data['server_qq']) == 0) $data['server_qq'] = Db::name("user")->where("username",'admin')->where("user_type","admin")->value("qq");
        return $data;
    }

    public function getinfo(){
        $data = array();
        $data['userinfo'] = $this->getUserInfo();
        $images = Db::name("adimages")->where("name","like","lunbo_%")->select();
        $adlist = array();
        $url =  'http://'.$_SERVER['HTTP_HOST'].'/';
        foreach($images as $image){
            if(strlen($image['filepath']) && strlen($image['link_url'])) $adlist[] = array("img"=>$url.$image['filepath'],'link'=>$image['link_url']);
        }
        $data['adimages'] = $adlist;
        $data['apiurl'] = Db::name('settings')->where('set_name','apiurl')->value('set_value');
        if(!empty($data['apiurl'])){
            $data['apiurl']=base64_encode($data['apiurl']).$this->key ;
        }
        $data['byapiurl'] = Db::name('settings')->where('set_name','byapiurl')->value('set_value');
        $data['appnotice'] = Db::name('settings')->where('set_name','appnotice')->value('set_value');
        $adlist = array();
        $images = Db::name("adimages")->where("name","like","screen_%")->select();
        $url =  'http://'.$_SERVER['HTTP_HOST'].'/';
        foreach($images as $image){
            if(strlen($image['filepath'])) $adlist[] = array("src"=>$url.$image['filepath'],'link'=>$image['link_url']);
        }
        $count = count($adlist);
        $img = array();
        if($count>0){
            $index = rand(0,$count);
            if($index==$count) $index = 0;
            $img = $adlist[$index];
            $data['screenImage'] = $img;
        }
        return $data;
    }

    public function userinfo(){
        $user = $this->getUserInfo();
        return $user ? ['code'=>1,'data'=>$user] : ['code'=>-1,'msg'=>'no-login'];
    }

    protected function get_client_ip($type = 0) {
        $type       =  $type ? 1 : 0;
        static $ip  =   NULL;
        if ($ip !== NULL) return $ip[$type];
        if(isset($_SERVER['HTTP_X_REAL_IP'])){//nginx 代理模式下，获取客户端真实IP
            $ip=$_SERVER['HTTP_X_REAL_IP'];
        }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {//客户端的ip
            $ip     =   $_SERVER['HTTP_CLIENT_IP'];
        }elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {//浏览当前页面的用户计算机的网关
            $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos    =   array_search('unknown',$arr);
            if(false !== $pos) unset($arr[$pos]);
            $ip     =   trim($arr[0]);
        }elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip     =   $_SERVER['REMOTE_ADDR'];//浏览当前页面的用户计算机的ip地址
        }else{
            $ip=$_SERVER['REMOTE_ADDR'];
        }
        // IP地址合法验证
        $long = sprintf("%u",ip2long($ip));
        $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
        return $ip[$type];
    }

    private function get_yqm($len=10){
        $str = "asdfghjklzxcvbnmoiuytrewqMNBVCXZASDFGHJKLPOIUYTREWQ0987654123";
        $yqm = "";
        for($i=0;$i<$len;$i++){
            $offset = mt_rand(0,strlen($str));
            $yqm .= substr($str,$offset,1);
        }
        return $yqm;
    }

    public  function  register(){
        if(!request()->isPost()) $this->error('请求类型有误');

        $tuijianma = input("tuijianma");
        if(strlen($tuijianma) == 0) return ['code'=>-1,'msg'=>'请填写邀请码'];
        $tuser = Db::name('user')->where('tuijianma',$tuijianma)->find();
        if(!$tuser) return ['code'=>-1,'msg'=>'邀请码不正确'];
        $uid = $tuser['id'];

        $uuid = strtolower(Request::instance()->header("device-info"));
        if(strlen($uuid) && Db::name('user')->where('uuid',$uuid)->count()>=2){
            return ['code'=>-1,'msg'=>'此设备已超过最大注册数，不能重复注册'];
        }

        $username = input("username");
        $password = input("password");
        $repassword = input("repassword");
        if(!preg_match("/^1[34578]\d{9}$/", $username)) return ['code'=>-1,'msg'=>'请填写正确的手机号'];
        if(strlen($password) <=5 ) return ['code'=>-1,'msg'=>'密码必填且不能小于6位'];
        if($password != $repassword) return ['code'=>-1,'msg'=>'两次密码不一致'];

        $finduid = intval(Db::name('user')->where('username',$username)->value('id'));
        if($finduid>0) return ['code'=>-1,'msg'=>'此手机号已注册，不能重复注册'];

        $data = array();
        $data['username'] = $username;
        $data['password'] = md5($password);
        $data['parent_id'] = $uid;
        $data['reg_time'] = time();
        $data['usernick'] = $username;
        $data['reg_ip'] = $this->get_client_ip();
        $data['uuid'] = $uuid;
        $data['regcode'] = $tuijianma;
        $data['user_type'] = 'member';
        $value = $this->get_yqm();
        while(Db::name("user")->where('tuijianma',$value)->find()){
            $value = $this->get_yqm();
        }
        $data['tuijianma'] = $value;
        Db::startTrans();
        try {
            if (Db::name("user")->insert($data)) {
                $uid = Db::getLastInsID();//新注册用户ID
                $free_times = intval(Db::name('settings')->where('set_name', 'freetimes')->value('set_value'));
                if ($free_times < 0) $free_times = 0;
                $data = array();
                $data['user_id'] = $uid;
                $data['free_times'] = $free_times;
                $data['end_time'] = time() + $free_times * 24 * 3600;
                if (Db::name("member_info")->insert($data)) {
                    $uid = $tuser['id'];//推荐人用户ID
                    //给推荐人增加推荐数
                    $data = Db::name("member_info")->where("user_id",$uid)->find();
                    if(!$data){
                        $data = array();
                        $data['tuijian_count'] = 0;
                        $data['offers_days'] = 0;
                        $data['end_time'] = $tuser['user_type'] == 'member' ? time() + $free_times * 24 * 3600 : 0;
                        $data['user_id'] = $uid;
                        if(Db::name("member_info")->insert($data)){
                            $data['id'] = Db::name("member_info")->getLastInsID();
                        }else{
                            Db::rollback();
                            return ['code' => -1, 'msg' => '未知错误，注册失败'];
                        }
                    }
                    $data['tuijian_count'] += 1;
                    //推荐奖励
                    if($tuser['user_type'] == 'member'){
                        $days = 0;
                        if($data['tuijian_count'] == 1 || $data['tuijian_count'] == 5 || $data['tuijian_count'] == 10){
                            $days = intval(Db::name("settings")->where('set_name','tuijian_'.$data['tuijian_count'])->value("set_value"));
                        }
                        if($days>0){
                            $data['offers_days'] += $days;
                            $data['end_time'] = $data['end_time']>=time() ? $data['end_time'] + $days * 24 * 3600 : time() + $days * 24 * 3600;
                        }
                    }
                    if(!Db::name("member_info")->where("id",$data['id'])->update($data)){
                        Db::rollback();
                        return ['code' => -1, 'msg' => '未知错误，注册失败'];
                    }

                    Db::commit();
                    return ['code' => 1, 'msg' => '注册成功'];
                }else{
                    Db::rollback();
                    return ['code' => -1, 'msg' => '未知错误，注册失败'];
                }
            } else {
                Db::rollback();
                return ['code' => -1, 'msg' => '未知错误，注册失败'];
            }
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();//var_dump($e);
            return ['code' => -1, 'msg' => '未知错误，注册失败'];
        }

    }

    public function login(){
        if(!request()->isPost()) ['code'=>-1,'msg'=>'请求类型有误'];
        $username = input("username");
        $password = input("password");
        if(!preg_match("/^1[34578]\d{9}$/", $username)) return ['code'=>-1,'msg'=>'请填写正确的手机号'];
        if(strlen($password) <=5 ) return ['code'=>-1,'msg'=>'密码必填且不能小于6位'];
        $uid = Db::name("user")->where("username",$username)->where("password",md5($password))->where("user_type","member")->value('id');
        if($uid>0){
            $token = $this->createJwt($uid);
            Db::name("user")->where("id",$uid)->setField('token',$token);
            Db::name("user")->where("id",$uid)->setField('last_login_time',time());
            //Session::init(['expire'=>604800]);//保存7天登陆状态
            //session("login_front_user_id",$uid);
            $info = $this->getUserInfo($uid);
            $info['token'] = $token;
            return ['code'=>1,'data'=>$info];
        }else{
            return ['code' => -1, 'msg' => '用户名或密码错误'];
        }

    }

    protected function createJwt($userId,$clear=false)
    {
        $key = md5('fdsfe4gfgs'); //jwt的签发密钥，验证token的时候需要用到
        $time = time(); //签发时间
        $expire = $clear ? 0 : $time + 2592000; //过期时间30天
        $token = array(
            "user_id" => $userId,
            "iss" => "",//签发组织
            "aud" => "", //签发作者
            "iat" => $time,
            "nbf" => $time,
            "exp" => $expire
        );
        $jwt = JWT::encode($token, $key);
        return $jwt;
    }

    //退出登陆
    public function logout(){
        $header = Request::instance()->header();
        if (isset($header['token']) && $header['token'] != 'null') {
            $uid = $this->verifyJwt($header['token']);
            $this->createJwt($uid,true);
        }
        return ['code'=>1,'msg'=>'退出登陆成功'];
    }

    public function canplay(){
        $user = $this->getUserInfo();
        if(!$user) return ['code'=>-1,'msg'=>'no-login'];
        if($user['end_time'] == '已到期' || $user['end_time']=='') return ['code'=>-1,'msg'=>'你没有观看权限，请购买卡密并激活后再试'];
        if($user['end_time']!='' && $user['end_time']!='已到期'){
            $video = Db::name("videos")->where("id",intval(input("id")))->find();
            if($video) Db::name("videos")->where("id",intval(input("id")))->setInc("play_times");
            $images = Db::name("adimages")->where("name","like","player_%")->select();
            $adlist = array();
            $url =  'http://'.$_SERVER['HTTP_HOST'].'/';
            foreach($images as $image){
                if(strlen($image['filepath']) && strlen($image['link_url'])) $adlist[] = array("img"=>$url.$image['filepath'],'link'=>$image['link_url']);
            }
            $count = count($adlist);
            $img = array();
            if($count>0){
                $index = rand(0,$count);
                if($index==$count) $index = 0;
                $img = $adlist[$index];
            }


            $data = array();
            if($img) $data['adImage'] = $img;
            $adText = Db::name("adimages")->where("name","text")->find();
            if($adText) $data['adText'] = array('text'=>$adText['filepath'],'link'=>$adText['link_url']);
            $systemText = Db::name("adimages")->where("name","system")->find();
            if($systemText) $data['systemText'] = array('text'=>$systemText['filepath'],'link'=>$systemText['link_url']);

            return ['code'=>1,'msg'=>'验证通过','data'=>$data];
        }else{
            return ['code'=>-1,'msg'=>'你没有观看权限，请购买卡密并激活后再试'];
        }
    }

    public function get_videos(){
        $user = $this->getUserInfo();
        $list = Db::name("videos")->field("id,title,img,address,play_times")->order("id","desc")->paginate(100);
        $list->each(function ($item,$index){
            $like = Db::name("collect")->where("video_id",$item['id'])->where("user_id",$this->user ? $this->user['id'] : 0)->find();
            $item['liked'] = $like && $like['isdelete']==0 ? true : false;
            return $item;
        });
        return ['code'=>1,'data'=>$list->items()];
    }
}
